package com.qo.qsdk.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ScreenUtil {

    private static int mStatusBarHeight = 0;
    private static int mNavigationBarHeight = 0;

    private static boolean mHasSoftwareKeys;
    private static boolean mHasSoftwareKeysCached = false;

    public static float density(Context context) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        return displayMetrics.density;
    }

    public static int densityDpi(Context context) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        return displayMetrics.densityDpi;
    }

    public static int dip2px(Context context, int dpValue) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        int i = displayMetrics.densityDpi;
        float f = i / 160.0F;
        return (int) (dpValue * f + 0.5F);
    }

    public static int px2dip(Context context, int pxValue) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        int i = displayMetrics.densityDpi;
        float f = i / 160.0F;
        return (int) (pxValue / f + 0.5F);
    }

    public static int px2sp(Context context, float px) {
        return (int) ((px / context.getResources().getDisplayMetrics().scaledDensity) + 0.5f);
    }

    public static int heightPixels(Context context) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        return displayMetrics.heightPixels;
    }

    public static int widthPixels(Context context) {
        DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics();
        return displayMetrics.widthPixels;
    }

    public static int min(Context context) {
        return Math.min(widthPixels(context), heightPixels(context));
    }

    public static int max(Context context) {
        return Math.max(widthPixels(context), heightPixels(context));
    }

    public static boolean isOrientationLandscape(Context context) {
        Context app = context.getApplicationContext();
        WindowManager windowManager = (WindowManager) app.getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);

        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        return height <= width;
    }

    public static boolean isActivityFullScreen(Activity activity) {
        WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
        return (attrs.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
    }

    @SuppressWarnings("all")
    public static int statusBarHeight(Context context) {
        if (mStatusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer)field.get(o);
                mStatusBarHeight = context.getResources().getDimensionPixelOffset(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mStatusBarHeight;
    }

    public static boolean hasSoftKeys(Context context) {
        try {
            return innerHasSoftKeys(context);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static int navigationBarHeight(Context context) {
        if (mNavigationBarHeight == 0) {
            try {
                Resources resources = context.getResources();
                int resourceId = resources.getIdentifier("navigation_bar_height",
                        "dimen", "android");
                mNavigationBarHeight = resources.getDimensionPixelSize(resourceId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return mNavigationBarHeight;
    }

    private static WindowManager getWindowManager(Context context) {
        WindowManager result = null;
        try {
            if (context instanceof Activity) {
                result = ((Activity) context).getWindowManager();
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = null;
        }

        if (result == null) {
            result = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }

        return result;
    }

    private static boolean innerHasSoftKeys(Context context) {
        if (!mHasSoftwareKeysCached) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {

                WindowManager wm = getWindowManager(context);
                if (wm != null) {
                    Display d = wm.getDefaultDisplay();

                    DisplayMetrics realDisplayMetrics = new DisplayMetrics();
                    d.getRealMetrics(realDisplayMetrics);

                    int realHeight = realDisplayMetrics.heightPixels;
                    int realWidth = realDisplayMetrics.widthPixels;

                    DisplayMetrics displayMetrics = new DisplayMetrics();
                    d.getMetrics(displayMetrics);

                    int displayHeight = displayMetrics.heightPixels;
                    int displayWidth = displayMetrics.widthPixels;

                    mHasSoftwareKeys = (realWidth > displayWidth) || (realHeight > displayHeight);
                    mHasSoftwareKeysCached = true;
                } else {
                    return false;
                }
            } else {
                boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
                boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
                mHasSoftwareKeys = !hasMenuKey && !hasBackKey;
                mHasSoftwareKeysCached = true;
            }
        }

        return mHasSoftwareKeys;
    }

    public static Bitmap captureActivity(Activity activity) {
        if (activity != null) {
            activity.getWindow().getDecorView().setDrawingCacheEnabled(true);
            return activity.getWindow().getDecorView().getDrawingCache();
        }

        return null;
    }

    /**
     * 获取屏幕尺寸，但是不包括虚拟功能高度
     *
     * @return
     */
    public static int getNoHasVirtualKey(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = windowManager.getDefaultDisplay().getHeight();
        return height;
    }


    /**
     * 通过反射，获取包含虚拟导航栏的整体屏幕高度
     *
     * @return
     */
    public static int getHasVirtualKey(Context context) {
        int dpi = 0;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            dpi = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }


    /**
     * 获取屏幕实际高度（也包含虚拟导航栏）
     *
     * @param context
     * @return
     */
    public static int getRealHight(Context context) {
        DisplayMetrics displayMetrics = null;
        if (displayMetrics == null) {
            displayMetrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        }
        return displayMetrics.heightPixels;
    }

    /**
     * 判断是否存在NavigationBar
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;

    }


    /**
     * 是否是华为
     */
    public static boolean isHUAWEI() {
        print(Build.MANUFACTURER);
        return Build.MANUFACTURER.equals("Huawei");
    }

    /**
     * 获取导航栏高度
     *
     * @param context
     * @return
     */
    public static int getNavigationBarHeight(Context context) {

        boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
        if (!hasMenuKey && !hasBackKey) {
            //没有物理按钮（虚拟导航栏）
            print("没有物理按钮（虚拟导航栏）");
            Resources resources = context.getResources();
            int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
            //获取NavigationBar的高度
            int height = resources.getDimensionPixelSize(resourceId);
            return height;
        } else {
            print("有物理导航栏，小米非全面屏");
            //有物理导航栏，小米非全面屏
            return 0;
        }
    }


    /**
     * 隐藏虚拟按键，并且设置成全屏
     */
    public static void hideBottomUIMenu(Context context) {
        Activity activity = null;
        if (context instanceof Activity) {
            activity = (Activity) context;
        }
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


    public static DisplayMetrics getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }

    /**
     * 获取屏幕分辨率高度 *
     */
    public static int getScreenHeight(Context context) {
        return getDisplayMetrics(context).heightPixels;
    }


    private static void print(String msg) {
        Log.i("Nj", msg);
    }
}
